package com.xr.blog.tools.camera;

import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.WebcamUtils;
import com.xr.blog.tools.storage.OSSFactory;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 抓拍工具类
 *
 * @author 幸仁杰
 * @Date 2020-09-10
 */
public class CameraUtils {

    public static void takePictures(){
        Webcam webcam = Webcam.getDefault();
        if (webcam != null) {
            String filePath = "C:"+File.separator+"picture"+File.separator+ new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            File path = new File(filePath);
            if (!path.exists()) {//如果文件不存在，则创建该目录
                path.mkdirs();
            }
            String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            File file = new File(filePath +File.separator+ time + ".jpg");
            webcam.setViewSize(WebcamResolution.VGA.getSize());
            WebcamUtils.capture(webcam, file);
            byte[] data=WebcamUtils.getImageBytes(webcam,"JPG");
            String url= OSSFactory.build().uploadSuffix(data, ".jpg");
            webcam.close();
            deleteFolder(path);
        }
    }


    public static void deleteFolder(File folder){
        File[] list = folder.listFiles();

        if(list!=null){
            for(File file:list){
                if(file.isDirectory()){
                    deleteFolder(file);
                }else{
                    file.delete();
                }
            }
        }
        folder.delete();
    }
}
